package common.utils;


import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 清风明月
 * @Package common.utils
 * @date 2025/4/30
 * @description 二维码生成器
 */
@SuppressWarnings("all")
public class QrCodeUtils {

    /**
     * 生成二维码并返回 Base64 编码字符串
     */
    public static String generateQrCode(String content) throws WriterException, IOException {
        // 设置二维码参数
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // 设置字符编码
        hints.put(EncodeHintType.ERROR_CORRECTION, com.google.zxing.qrcode.decoder.ErrorCorrectionLevel.M); // 设置纠错级别
        hints.put(EncodeHintType.MARGIN, 1); // 设置边距

        // 创建二维码生成器
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        try {
            // 生成二维码的位矩阵
            BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, 300, 300, hints);
            // 将位矩阵转换为图片并输出到字节数组
            BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "PNG", byteArrayOutputStream);
            String base64EncodedString = Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray());
            return base64EncodedString; // 返回二维码图片的 Base64 编码字符串

        } catch (WriterException | IOException e) {
            e.printStackTrace();
            throw new RuntimeException("生成二维码失败", e);
        }
    }

}
